#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
#include "methodpost.h"
#include "templates.h"

void PrintInfo(char * fileName)
{
	FILE * formData = fopen(ToLower(fileName), "rt");
	if (!formData)
	{
		printf("<ul>\n<li>This user does not exist.</li>\n</ul>");
		return;
	}
	char buf[255];
	printf("<ul>\n");
	fgets(buf, 255, formData);
	printf("<li><span>First Name:</span> %s</li>\n", buf);
	fgets(buf, 255, formData);
	printf("<li><span>Last Name:</span> %s</li>\n", buf);
	fgets(buf, 255, formData);
	printf("<li><span>E-Mail:</span> %s</li>\n", buf);
	fgets(buf, 255, formData);
	printf("<li><span>Password:</span> %s</li>\n", buf);
	fgets(buf, 255, formData);
	if (strcmp(buf, "none") != 0)
	{
		printf("<li><span>Sex:</span> %s</li>\n", buf);
	}
	fgets(buf, 255, formData);
	strcmp(buf, "none") == 0 ? printf("<li><span>Birthday:</span> **/") : printf("<li><span>Birthday:</span> %s/", buf);
	fgets(buf, 255, formData);
	strcmp(buf, "none") == 0 ? printf("**/") : printf("%s/", buf);
	fgets(buf, 255, formData);
	strcmp(buf, "none") == 0 ? printf("**</li>\n") : printf("%s</li>\n", buf);
	printf("</ul>\n");
	fclose(formData);
	formData = NULL;
}

void GetFileName(void)
{
	size_t n = atoi(getenv("CONTENT_LENGTH"));
	char * data = (char *)malloc(n + 2);
	memset(data, '\0', n + 2);
	fread(data + 1, 1, n + 1, stdin);
	data[0] = '?';

	char fileName[255];
	if (!(GetValue("email", data, fileName)))
	{
		printf("<ul>\n<li><span>ERROR: </span>You have not entered e-mail!</li>\n</ul>\n");
		return;
	}
	char * extension = ".txt";
	strncat(fileName, extension, strlen(extension));
	free(data);
	PrintInfo(fileName);	
}

void main(void)
{
	PrintHTTPResponseHeader();
	PrintHTMLHead("Result", "Result", "All information entered by the user.");
	GetFileName();
	PrintHTMLEnd();
}